<template>
  <div class="home">
    <div class="news-detail">
      <!-- 加载状态 -->
      <el-skeleton :loading="loading" animated :rows="10" v-if="loading">
        <template #template>
          <div style="padding: 20px">
            <el-skeleton-item variant="h1" style="width: 80%" />
            <div style="margin: 20px 0">
              <el-skeleton-item variant="text" style="margin-right: 16px" />
              <el-skeleton-item variant="text" style="width: 30%" />
            </div>
            <el-skeleton-item variant="p" style="width: 100%" />
            <el-skeleton-item variant="p" style="width: 100%" />
            <el-skeleton-item variant="p" style="width: 100%" />
          </div>
        </template>
      </el-skeleton>

      <!-- 错误状态 -->
      <template v-else-if="error">
        <div class="error-container">
          <el-result
              icon="error"
              :title="error.title"
              :sub-title="error.message"
          >
            <template #extra>
              <el-button type="primary" @click="retryFetch">重试</el-button>
              <el-button @click="$router.push('/')">返回首页</el-button>
            </template>
          </el-result>
        </div>
      </template>

      <template v-else>
        <div class="content-grid">
          <!-- 新闻内容 -->
          <div class="news-content">
            <h1 class="title">{{ news.title }}</h1>

            <div class="meta">
              <span class="source">{{ news.source }}</span>
              <span class="time">{{ news.time }}</span>
              <el-tag type="info" size="small">{{ news.category }}</el-tag>
              <span class="author" v-if="news.author">{{ news.author }}</span>
            </div>

            <!-- 文章内容 -->
            <div class="content">
              <!-- HTML 内容 -->
              <div
                  v-if="isHtmlContent"
                  v-html="news.content"
                  class="html-content"
              ></div>

              <!-- 纯文本内容 -->
              <template v-else>
                <p>
                  {{ news.content }}
                </p>
              </template>

              <!-- 图片展示 -->
              <div
                  v-for="(image, index) in news.images"
                  :key="'image-' + index"
                  class="image-container"
              >
                <el-image
                    :src="image.url"
                    :alt="image.caption"
                    fit="cover"
                    class="content-image"
                    :preview-src-list="news.images.map((img) => img.url)"
                    :initial-index="index"
                    lazy
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>图片加载失败</span>
                    </div>
                  </template>
                </el-image>
                <p class="image-caption">{{ image.caption }}</p>
              </div>

              <!-- 引用块 -->
              <div class="quote" v-if="news.quote">
                <p>{{ news.quote }}</p>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button
                  :type="news.isLiked ? 'success' : 'default'"
                  :icon="news.isLiked ? SuccessFilled : Pointer"
                  @click="handleLike"
                  class="action-button"
              >
                {{ news.isLiked ? "已点赞" : "点赞" }}
              </el-button>

              <el-button
                  :type="news.isFavorited ? 'warning' : 'default'"
                  :icon="news.isFavorited ? 'Star' : 'Star'"
                  @click="handleFavorite"
                  class="action-button"
              >
                {{ news.isFavorited ? "已收藏" : "收藏" }}
                <span class="count" v-if="news.favoriteCount">{{
                    news.favoriteCount
                  }}</span>
              </el-button>

              <el-button
                  type="danger"
                  :icon="Warning"
                  @click="handleReport"
                  class="action-button"
              >
                举报
              </el-button>
            </div>

            <!-- 相关新闻 -->
            <div class="related-section">
              <h3>相关新闻</h3>
              <div class="related-list">
                <div
                    v-for="item in relatedNews"
                    :key="item.id"
                    class="related-item"
                >
                  <router-link :to="`/news/${item.id}`" class="related-link">
                    {{ item.title }}
                  </router-link>
                  <span class="related-time">{{ item.time }}</span>
                </div>
              </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-section">
              <!-- 评论输入框 -->
              <div class="comment-input">
                <el-input
                  v-model="commentText"
                  type="textarea"
                  :rows="3"
                  placeholder="写下你的评论..."
                  resize="none"
                ></el-input>
                <div class="comment-actions">
                  <el-button type="primary" @click="submitComment"
                    >发表评论</el-button
                  >
                </div>
              </div>

              <h2>评论 ({{ comments.total }})</h2>
              <div class="comment-list">
                <div v-if="comments.list.length === 0" class="no-comments">
                  <el-empty description="暂无评论" />
                </div>
                <div
                  v-else
                  v-for="comment in comments.list"
                  :key="comment.id"
                  class="comment-item"
                >
                  <el-avatar
                    :size="40"
                    :src="comment.avatar"
                    class="comment-avatar"
                  />
                  <div class="comment-content">
                    <div class="comment-header">
                      <span class="username">{{ comment.username }}</span>
                      <span class="time">{{ formatTime(comment.time) }}</span>
                      <!-- <span class="like-count" v-if="comment.likeCount > 0">
                        <el-icon><Star /></el-icon>
                        {{ comment.likeCount }}赞
                      </span> -->
                      <!-- 回复按钮 -->
                      <el-button
                        type="text"
                        size="small"
                        @click="toggleReplyInput(comment.id)"
                        class="reply-button"
                      >
                        回复
                      </el-button>
                      <!-- 删除按钮 -->
                      <el-button
                        v-if="userStore.userInfo?.id === comment.userId"
                        type="text"
                        size="small"
                        @click="deleteComment(comment.id)"
                        class="delete-button"
                      >
                        删除
                      </el-button>
                    </div>

                    <div class="comment-text">{{ comment.content }}</div>

                    <!-- 回复输入框 -->
                    <div v-if="activeReplyId === comment.id" class="reply-input">
                      <el-input
                        v-model="replyText"
                        type="textarea"
                        :rows="2"
                        placeholder="写下你的回复..."
                        resize="none"
                      ></el-input>
                      <div class="reply-actions">
                        <el-button size="small" @click="cancelReply">取消</el-button>
                        <el-button type="primary" size="small" @click="submitReply(comment.id)">提交</el-button>
                      </div>
                    </div>

                    <!-- 子评论部分 -->
                    <div v-if="comment.childComments && comment.childComments.length > 0" class="child-comments">
                      <div class="toggle-replies" @click="toggleReplies(comment.id)">
                        <el-button type="text" class="toggle-button">
                          <el-icon class="toggle-icon">
                            <component :is="showAllReplies[comment.id] ? ArrowUp : ArrowDown" />
                          </el-icon>
                          {{ showAllReplies[comment.id] ? '收起回复' : `展开${comment.childComments.length}条回复` }}
                        </el-button>
                      </div>

                      <div v-show="showAllReplies[comment.id]" class="child-comments-container">
                        <div v-for="childComment in comment.childComments"
                             :key="childComment.commentId"
                             class="child-comment-item">
                          <el-avatar
                            :size="30"
                            :src="childComment.avatar || doro"
                            class="comment-avatar"
                          />
                          <div class="child-comment-content">
                            <div class="comment-header">
                              <span class="username">{{ childComment.userName }}</span>
                              <span class="time">{{ formatTime(childComment.createTime) }}</span>
                              <span class="like-count" v-if="childComment.likeCount > 0">
                                <el-icon><Star /></el-icon>
                                {{ childComment.likeCount }}赞
                              </span>
                              <!-- 子评论删除按钮 -->
                              <el-button
                                v-if="userStore.userInfo?.id === childComment.userId"
                                type="text"
                                size="small"
                                @click="deleteComment(childComment.commentId)"
                                class="delete-button"
                              >
                                删除
                              </el-button>
                            </div>
                            <div class="comment-text">{{ childComment.commentText }}</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 加载更多按钮 -->
                <div v-if="comments.hasMore" class="load-more-comments">
                  <el-button type="text" class="toggle-button" @click="loadMoreComments">
                    <el-icon class="toggle-icon"><ArrowDown /></el-icon>
                    加载更多评论
                  </el-button>
                </div>
              </div>

            </div>
          </div>

          <!-- 右侧相关新闻 -->
          <div class="sidebar">
            <div class="hot-news">
              <h3>
                <el-icon><Top /></el-icon> 热点排行
              </h3>
              <div class="hot-list">
                <div
                    v-for="item in hotNews"
                    :key="item.id"
                    class="hot-item"
                    :class="{ 'top-three': item.index <= 3 }"
                >
                  <span class="hot-rank">{{ item.index }}</span>
                  <router-link :to="`/news/${item.id}`" class="hot-link">
                    {{ item.title }}
                  </router-link>
                  <!-- <span class="hot-views">
                    <el-icon><Star /></el-icon> {{ item.views }}
                  </span> -->
                </div>
              </div>
            </div>

                        <div class="ad-container">
              <a @click="handleAdClick" href="javascript:void(0)">
                <el-image
                  :src="currentAd.image"
                  fit="cover"
                  class="ad-image"
                  @error="handleAdError"
                />
                <p class="ad-text">{{ currentAd.text }}</p>
              </a>
            </div>
          </div>
        </div>
      </template>
    </div>
    <el-dialog
        title="举报内容"
        v-model="reportDialogVisible"
        width="500px"
        @close="handleDialogClose"
    >
      <div style="display: flex; flex-direction: column; gap: 12px; margin-top: 12px;">
        <el-select
            v-model="reportForm.violationType"
            placeholder="请选择举报类型"
            style="width: 100%;"
        >
          <el-option label="广告" value="spam" />
          <el-option label="色情" value="porn" />
          <el-option label="虚假信息" value="fake" />
          <el-option label="暴力内容" value="violence" />
          <el-option label="其他" value="other" />
        </el-select>
        <el-input
            type="textarea"
            placeholder="请输入举报描述"
            v-model="reportForm.description"
            :rows="4"
        ></el-input>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReport">提交举报</el-button>
        </span>
      </template>
    </el-dialog>
  </div>


</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import { useRoute } from "vue-router";
import {
  Top,
  View,
  Picture,
  Star,
  Pointer,
  Warning,
  SuccessFilled,
  ArrowDown,
  ArrowUp
} from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { onBeforeUnmount } from "vue";
import { useUserStore } from "@/store/user";
import doro from "/public/images/doro.jpg";

const doroUrl = ref("/public/images/doro.jpg");
const route = useRoute();
const commentText = ref("");
const replyText = ref("");
const activeReplyId = ref(null);
const news = ref({});
const loading = ref(false);
const error = ref(null);
const comments = ref({
  total: 0,
  list: [],
  pageNum: 1,
  pageSize: 10,
  hasMore: true
});
const totalPage = ref(0);
const relatedNews = ref([]);
const hotNews = ref([]);
const userId = ref(0);
const pendingLikeOperations = ref({});
const userStore = useUserStore();
const showAllReplies = ref({});
const ads = [
  {
    image: "/images/AD/AD1.jpg",
    text: '心相印抽纸茶语纸巾面巾纸卫生纸茶叶压花擦手巾母婴适用便携纸抽...',
    href:"https://detail.tmall.com/item.htm?detail_redpacket_pop=true&id=902326618710&mi_id=ZRmxDX6D8evs049cLxgDTSDuqEHPqTzSfc5InzBhrXWhs_YV_3Ofdu_RSaTTYU8Nq79054HwmBS44DsRVKNZq20KChNoYCqWm4GTXMxtX18&ns=1&priceTId=undefined&query=%E5%BF%83%E7%9B%B8%E5%8D%B0%E6%8A%BD%E7%BA%B8%E8%8C%B6%E8%AF%AD%E7%BA%B8%E5%B7%BE%E9%9D%A2%E5%B7%BE%E7%BA%B8%E5%8D%AB%E7%94%9F%E7%BA%B8%E8%8C%B6%E5%8F%B6%E5%8E%8B%E8%8A%B1%E6%93%A6%E6%89%8B%E5%B7%BE%E6%AF%8D%E5%A9%B4%E9%80%82%E7%94%A8%E4%BE%BF%E6%90%BA%E7%BA%B8%E6%8A%BD&skuId=5761482153203&spm=a21n57.1.hoverItem.6&utparam=%7B%22aplus_abtest%22%3A%2228cd030ce451473b22f84fc5d534331a%22%7D&xxc=ad_ztc"
  },
  {
    image: "/images/AD/AD2.jpg",
    text: '植宴 小鱼花生米下酒菜开袋即食500g罐多味油炸花生零食小吃...',
    href:"https://detail.tmall.com/item.htm?abbucket=2&detail_redpacket_pop=true&id=935402128000&mi_id=ShfN7fmMUiVlJdyfPXQX-6IvuxXVRJnRwJIcGCWciwsl4Ds-NGIhnftfrZL-5kr9B_87zx06JaS3Oa8bDsF1mpr9AWHDRMJx8R6obTn9v2Y&ns=1&priceTId=2150433317509066459111015e194e&query=%E6%A4%8D%E5%AE%B4%20%E5%B0%8F%E9%B1%BC%E8%8A%B1%E7%94%9F%E7%B1%B3%E4%B8%8B%E9%85%92%E8%8F%9C%E5%BC%80%E8%A2%8B%E5%8D%B3%E9%A3%9F500g%E7%BD%90%E5%A4%9A%E5%91%B3%E6%B2%B9%E7%82%B8%E8%8A%B1%E7%94%9F%E9%9B%B6%E9%A3%9F%E5%B0%8F%E5%90%83&skuId=5994144278682&spm=a21n57.1.hoverItem.2&utparam=%7B%22aplus_abtest%22%3A%228d9cf80ec1cf541186905a56df403215%22%7D&xxc=taobaoSearch"
  },
  {
    image: "/images/AD/AD3.jpg",
    text: '【国货正品】新疆乌斯曼草洗发皂手工白发乌发养发重度植物精华皂...',
    href:"https://item.taobao.com/item.htm?abbucket=2&detail_redpacket_pop=true&id=852112650094&mi_id=U2y7acBYpkdHtwl98FStDmmxQvNiu-W028hE3UIQbJvCy7IWZgR1rHkI2-WxkCnjl3aW2pss2J7fxrByf48wfY7rvWX67mQVvL5Zo95uKhg&ns=1&priceTId=undefined&query=%E3%80%90%E5%9B%BD%E8%B4%A7%E6%AD%A3%E5%93%81%E3%80%91%E6%96%B0%E7%96%86%E4%B9%8C%E6%96%AF%E6%9B%BC%E8%8D%89%E6%B4%97%E5%8F%91%E7%9A%82%E6%89%8B%E5%B7%A5%E7%99%BD%E5%8F%91%E4%B9%8C%E5%8F%91%E5%85%BB%E5%8F%91%E9%87%8D%E5%BA%A6%E6%A4%8D%E7%89%A9%E7%B2%BE%E5%8D%8E%E7%9A%82&skuId=5816639718119&spm=a21n57.1.hoverItem.9&utparam=%7B%22aplus_abtest%22%3A%22c11c1d1c77d2f964780e3af0d2468afd%22%7D&xxc=taobaoSearch"
  },
  {
    image: "/images/AD/AD4.png",
    text: '澳朵姿法国香水洗衣液COCO蓝风铃香氛皂液72小时持久留香迪...',
    href:"https://item.taobao.com/item.htm?abbucket=2&detail_redpacket_pop=true&id=618882907914&mi_id=GpHW_zBFOetqwexGjj_bYPqPoJ0KkWR3mApR_rjk1n5W3qMU3at5JuTAeq_MHWIneACftBU_SjNAGYqq19zDfVaJZP27jfEF_mR08STCUCk&ns=1&priceTId=undefined&query=%E6%BE%B3%E6%9C%B5%E5%A7%BF%E6%B3%95%E5%9B%BD%E9%A6%99%E6%B0%B4%E6%B4%97%E8%A1%A3%E6%B6%B2COCO%E8%93%9D%E9%A3%8E%E9%93%83%E9%A6%99%E6%B0%9B%E7%9A%82%E6%B6%B272%E5%B0%8F%E6%97%B6%E6%8C%81%E4%B9%85%E7%95%99%E9%A6%99%E8%BF%AA&skuId=4367423165258&spm=a21n57.1.hoverItem.6&utparam=%7B%22aplus_abtest%22%3A%22fcfa8d664a6b505c9c0d30398b9c9047%22%7D&xxc=taobaoSearch"
  }
];
const currentAd = ref(ads[Math.floor(Math.random() * ads.length)]);

// 举报相关状态
const reportDialogVisible = ref(false);
const reportForm = ref({
  violationType: '',
  description: ''
});

const handleAdError = (e) => {
  e.target.src = 'https://via.placeholder.com/300x250?text=广告加载中...';
};
const handleAdClick = () => {
  if (currentAd.value.href) {
    window.open(currentAd.value.href, '_blank');
  }
};
// 判断内容是否为HTML
const isHtmlContent = computed(() => {
  if (!news.value?.content) return false;
  const content = news.value.content;
  // 检查是否包含HTML标签
  return /<[a-z][\s\S]*>/i.test(content);
});

// 将内容按段落分割（用于纯文本显示）
const contentParagraphs = computed(() => {
  if (!news.value?.content || isHtmlContent.value) return [];
  return news.value.content.split("\n").filter((p) => p.trim());
});

// 获取热门新闻
const fetchHotNews = async () => {
  try {
    const response = await axios.get("/app/news/hotNews?limit=5");
    if (response.data.code === 200) {
      hotNews.value = response.data.data.map((news, index) => ({
        id: news.id,
        title: news.title,
        views: `${news.likeCount || 0} 赞`,
        index: index + 1,
      }));
    }
  } catch (error) {
    console.error("获取热门新闻失败:", error);
    // 保持原有的静态数据作为后备
    hotNews.value = [
      { id: 2001, title: "日本计划大幅提高外国游客消费税", views: "0 赞" },
      { id: 2002, title: "中国游客在日遇袭事件最新进展", views: "0 赞" },
      { id: 2003, title: "日本政府启动'违法外国人清零'计划", views: "0 赞" },
    ];
  }
};

// 获取相关新闻
const fetchRelatedNews = async (newsId) => {
  try {
    const response = await axios.get(`/app/news/related/${newsId}?limit=4`);
    if (response.data.code === 200) {
      relatedNews.value = response.data.data.map((news) => ({
        id: news.id,
        title: news.title,
        time: formatTime(news.createDate),
      }));
    }
  } catch (error) {
    console.error("获取相关新闻失败:", error);
    // 保持原有的静态数据作为后备
    relatedNews.value = [
      {
        id: 1002,
        title: "日本计划提高外国游客消费税，影响旅游业发展",
        time: "2025-06-10",
      },
      {
        id: 1003,
        title: "大阪餐馆拒绝中国客人引争议，公司道歉",
        time: "2025-05-12",
      },
      {
        id: 1004,
        title: "日本启动'违法外国人清零'计划，加强入境管理",
        time: "2025-06-06",
      },
    ];
  }
};

// 获取新闻详情
const fetchNewsDetail = async (newsId) => {
  loading.value = true;
  error.value = null;
  try {
    const response = await axios.get(`/app/news/detail/${newsId}`);

    if (response.data.code === 200 && response.data.data) {
      const newsData = response.data.data;

      // 获取点赞状态
      if (userStore.token) {
        const likedIds = await axios
          .get(`/app/like/userLikes?userId=${userStore.userInfo.id}`)
          .then((res) => (res.data.code === 200 ? res.data.data : []))
          .catch(() => []);

        newsData.isLiked = likedIds.includes(parseInt(newsId));

        // 获取收藏状态
        const favResponse = await axios.get(
          `/app/favorites/check/${userStore.userInfo.id}/${newsId}`
        );
        newsData.isFavorited = favResponse.data.code === 200 && favResponse.data.data;
      } else {
        newsData.isLiked = false;
        newsData.isFavorited = false;
      }

      // 转换数据格式以匹配前端显示需求
      news.value = {
        id: newsData.id,
        title: newsData.title,
        content: newsData.content,
        contentParagraphs: contentParagraphs.value,
        source: "课头条",
        time: newsData.createDate,
        category: getCategoryName(newsData.categoryId),
        author: newsData.author,
        authorId: newsData.authorId,
        images: newsData.picPath
          ? [
              {
                url: newsData.picPath,
                caption: newsData.summary || newsData.title,
              },
            ]
          : [],
        quote: newsData.summary,
        isLiked: newsData.isLiked,
        isFavorited: newsData.isFavorited,
      };

      // 获取热门新闻
      await fetchHotNews();

      // 获取相关新闻
      await fetchRelatedNews(newsId);
    } else {
      error.value = {
        title: "获取新闻失败",
        message: "新闻不存在或已被删除",
      };
    }
  } catch (err) {
    console.error("获取新闻详情失败:", err);
    error.value = {
      title: "获取新闻失败",
      message: err.response?.data?.msg || "服务器错误，请稍后重试",
    };
  } finally {
    loading.value = false;
  }
};

const toggleReplies = (commentId) => {
  showAllReplies.value[commentId] = !showAllReplies.value[commentId];
};

// 获取评论列表的方法
const fetchComments = async () => {
  try {
    const response = await axios.get(`/app/comments/list/${route.params.id}?pageNo=${comments.value.pageNum}&pageSize=${comments.value.pageSize}`);
    if (response.data.code === 200) {
      const commentData = response.data.data;
      totalPage.value = commentData.totalPage;
      if (comments.value.pageNum === 1) {
        // 第一页时重置整个列表
        comments.value = {
          ...comments.value,
          total: commentData.total,
          list: commentData.list.map((comment) => ({
            id: comment.commentId,
            userId: comment.userId,
            username: comment.userName,
            avatar: comment.avatar || doroUrl,
            content: comment.commentText,
            time: comment.createTime,
            likeCount: comment.likeCount,
            childComments: comment.childrenComments || []
          })),
          hasMore: commentData.total > commentData.list.length
        };
      } else {
        // 加载更多时只追加列表
        const newComments = commentData.list.map((comment) => ({
          id: comment.commentId,
          userId: comment.userId,
          username: comment.userName,
          avatar: comment.avatar || doroUrl,
          content: comment.commentText,
          time: comment.createTime,
          likeCount: comment.likeCount,
          childComments: comment.childrenComments || []
        }));
        comments.value.list.push(...newComments);
        comments.value.total = commentData.total;
        comments.value.hasMore = comments.value.total > comments.value.list.length;
      }
    }
  } catch (error) {
    console.error("获取评论列表失败:", error);
    ElMessage.error("获取评论列表失败");
  }
};

const loadMoreComments = async () => {
  comments.value.pageNum += 1;
  await fetchComments();
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return "";
  const date = new Date(timeString);
  const now = new Date();
  const diff = now - date;

  // 小于1分钟
  if (diff < 60000) {
    return "刚刚";
  }
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }
  // 小于24小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }
  // 小于30天
  if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`;
  }
  // 大于30天，显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
      2,
      "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

// 删除评论
const deleteComment = async (commentId) => {
  try {
    const response = await axios.delete(`/app/comments/delete/${commentId}`);
    if (response.data.code === 200) {
      ElMessage.success("评论删除成功");
      // 重新获取评论列表
      await fetchComments();
    } else {
      ElMessage.error(response.data.message || "删除评论失败");
    }
  } catch (error) {
    console.error("删除评论失败:", error);
    ElMessage.error("删除评论失败");
  }
};

const toggleReplyInput = (commentId) => {
  if (activeReplyId.value === commentId) {
    activeReplyId.value = null;
  } else {
    activeReplyId.value = commentId;
    replyText.value = '';
  }
};

const cancelReply = () => {
  activeReplyId.value = null;
  replyText.value = '';
};

const submitReply = async (parentCommentId) => {
  if (!replyText.value.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }

  if (!userStore.token) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    // 1. 先保存回复内容（因为后面会清空输入框）
    const replyContent = replyText.value.trim();
    
    // 2. 查找被回复的评论内容和用户ID
    let repliedContent = '';
    let repliedUserId = null;
    let parentComment = null;
    
    // 在顶级评论中查找
    parentComment = comments.value.list.find(c => c.id === parentCommentId);
    if (parentComment) {
      repliedContent = parentComment.content;
      repliedUserId = parentComment.userId;
    } else {
      // 在回复中查找
      for (const comment of comments.value) {
        const reply = comment.childComments?.find(r => r.commentId === parentCommentId);
        if (reply) {
          repliedContent = reply.commentText;
          repliedUserId = reply.userId;
          parentComment = comment; // 保存父评论引用
          break;
        }
      }
    }

    // 3. 提交回复
    const response = await axios.post('/app/comments/add', {
      contentId: route.params.id,
      commentText: replyContent,
      parentCommentId: parentCommentId,
      userId: userStore.userInfo.id
    });

    if (response.data.code === 200) {
      ElMessage.success('回复成功');
      replyText.value = '';
      activeReplyId.value = null;
      
      // 4. 更新前端状态
      if (parentComment) {
        // 确保childComments数组存在
        if (!parentComment.childComments) {
          parentComment.childComments = [];
        }
        
        // 添加新回复到数组开头
        parentComment.childComments.unshift({
          commentId: response.data.data.commentId,
          userId: userStore.userInfo.id,
          userName: userStore.userInfo.username,
          avatar: userStore.userInfo.avatar || "https://via.placeholder.com/40x40?text=头像",
          commentText: replyContent,
          createTime: new Date().toISOString()
        });
        fetchComments();
        // 确保显示回复区域
        showAllReplies.value[parentCommentId] = true;
      }
      
      // 5. 发送系统通知（如果不是回复自己）
      if (repliedUserId && repliedUserId !== userStore.userInfo.id) {
        try {
          const noticeResponse = await axios.post("/api/systemNotice/add", {
            content: replyContent,  // 当前用户的回复内容
            createTime: new Date().toISOString(),
            userId: repliedUserId,
            status: "unread",
            title: `${userStore.userInfo.username}回复了你的评论: ${repliedContent.substring(0, 30)}${repliedContent.length > 30 ? '...' : ''}`,
            type: "reminder"
          });
          
          if (noticeResponse.data.code !== 200) {
            console.error("发送通知失败:", noticeResponse.data.msg);
          }
        } catch (noticeError) {
          console.error("发送通知出错:", noticeError);
        }
      }
    } else {
      ElMessage.error(response.data.message || '回复失败');
    }
  } catch (error) {
    console.error('回复失败:', error);
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg);
    } else {
      ElMessage.error('回复失败');
    }
  }
};

const submitComment = async () => {
  if (!commentText.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }
   // 1. 先保存评论内容（因为后面会清空）
    const commentContent = commentText.value.trim();

  try {
    const response = await axios.post("/app/comments/add", {
      contentId: route.params.id,
      commentText: commentContent,
      parentCommentId: null, //
      userId: userStore.userInfo.id
    });

    if (response.data.code === 200) {
      ElMessage.success("评论发布成功");
      commentText.value = "";
      // 重新获取评论列表
      await fetchComments();
      // 3. 发送系统通知给文章作者（如果不是作者自己评论的话）
      if (news.value.authorId && news.value.authorId !== userStore.userInfo?.id) {
        try {
          await axios.post("/api/systemNotice/add", {
            content: commentContent,
            createTime: new Date().toISOString(),
            userId: news.value.authorId,
            status: "unread",
            title: `${userStore.userInfo?.username || '匿名用户'}评论了文章：${news.value.title}`,
            type: "reminder"
          });
        } catch (noticeError) {
          console.error("发送通知失败:", noticeError);
          // 不显示错误给用户，避免影响评论体验
        }
      }
    } else {
      ElMessage.error(response.data.message || "评论发布失败");
    }
  } catch (error) {
    console.error("发布评论失败:", error);
    ElMessage.error("发布评论失败");
  }
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  const categoryMap = {
    1: "科技",
    2: "国际",
    3: "国内",
    4: "体育",
    5: "娱乐",
    6: "财经",
  };
  return categoryMap[categoryId] || "其他";
};

// 处理点赞
const handleLike = () => {
  if (!parseInt(userStore.userInfo?.id)) {
    ElMessage.warning("请先登录");
    return;
  }

  const currentNewsId = parseInt(route.params.id);
  const wasLiked = news.value.isLiked;

  // 1. 更新本地状态
  news.value.isLiked = !wasLiked;

  // 2. 记录待处理操作（覆盖之前的操作）
  pendingLikeOperations.value[currentNewsId] = wasLiked ? "cancel" : "add";

  ElMessage.success(news.value.isLiked ? "已点赞" : "已取消点赞");
};

// 提交待处理的点赞操作
const submitPendingLikeOperations = () => {
  if (Object.keys(pendingLikeOperations.value).length === 0) return;

  const currentUserId = userStore.userInfo?.id;
  if (!currentUserId) {
    pendingLikeOperations.value = {};
    return;
  }

  // 构建批量操作请求体
  const operations = Object.entries(pendingLikeOperations.value).map(
      ([contentId, type]) => ({
        type,
        userId: parseInt(currentUserId),
        contentId: parseInt(contentId),
      })
  );

  // 使用 navigator.sendBeacon 确保页面关闭时也能发送
  const url = "/app/like/batch";
  const data = JSON.stringify({ operations });

  if (navigator.sendBeacon) {
    const blob = new Blob([data], { type: "application/json" });
    navigator.sendBeacon(url, blob);
  } else {
    // 兼容不支持 sendBeacon 的浏览器
    axios.post(url, { operations }).catch(console.error);
  }

  // 清空待处理操作
  pendingLikeOperations.value = {};
};

// 处理收藏
const handleFavorite = async () => {
  if (!parseInt(userStore.userInfo?.id)) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    const userId = userStore.userInfo.id;
    const contentId = route.params.id;
    const isFavorited = news.value.isFavorited;

    // 根据当前状态调用不同接口
    const url = isFavorited
      ? `/app/favorites/cancel/${userId}/${contentId}`
      : `/app/favorites/add/${userId}/${contentId}`;

    const response = await axios.post(url);

    if (response.data.code === 200) {
      news.value.isFavorited = !isFavorited;
      ElMessage.success(news.value.isFavorited ? "收藏成功" : "已取消收藏");
    } else {
      ElMessage.error(response.data.message || "操作失败");
    }
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
};

// 处理举报
const handleReport = () => {
  if (!parseInt(userStore.userInfo?.id)) {
    ElMessage.warning("请先登录");
    return;
  }

  // 重置表单
  reportForm.value.violationType = ''
  reportForm.value.description = ''
  reportDialogVisible.value = true
}

// 提交举报
const submitReport = async () => {
  if (!reportForm.value.violationType) {
    ElMessage.warning("请选择举报类型");
    return;
  }

  try {
    const response = await axios.post("/app/violation/add", {
      contentId: parseInt(route.params.id),
      violationType: reportForm.value.violationType,
      description: reportForm.value.description
    });

    if (response.data.code === 200) {
      ElMessage.success("举报成功，感谢您的反馈！");
      reportDialogVisible.value = false // 关闭弹窗
    } else {
      ElMessage.error(response.data.message || "举报失败");
    }
  } catch (err) {
    console.error("举报操作失败:", err);
    ElMessage.error("操作失败，请稍后重试");
  }
}

// 关闭弹窗时重置表单
const handleDialogClose = () => {
  reportForm.violationType = ''
  reportForm.description = ''
}
// 重试获取数据
const retryFetch = async () => {
  if (route.params.id) {
    error.value = null; // 清除错误状态
    await Promise.all([fetchNewsDetail(route.params.id), fetchComments()]);
  } else {
    error.value = {
      title: "参数错误",
      message: "未找到新闻ID",
    };
  }
};

// 监听路由变化
watch(
    () => route.params.id,
    (newId) => {
      if (newId) {
        fetchNewsDetail(newId);
      }
    }
);

onMounted(() => {
  if (route.params.id) {
    fetchNewsDetail(route.params.id);
    fetchComments(); // 获取评论列表
  } else {
    error.value = {
      title: "参数错误",
      message: "未找到新闻ID",
    };
  }
});

// 新增：在页面卸载前提交操作
onBeforeUnmount(submitPendingLikeOperations);

// 新增：监听页面刷新/关闭事件
window.addEventListener("beforeunload", submitPendingLikeOperations);
</script>

<style scoped>

.home {
  min-height: 100vh;
  /* 添加背景图片 */
  background-image: url("/images/backgroundImages/blueArchive2.jpg"); /* 图片路径 */
  background-size: cover; /* 覆盖整个区域 */
  background-position: center; /* 居中显示 */
  background-repeat: no-repeat; /* 不重复 */
  background-attachment: fixed; /* 固定背景 */
}

.news-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  margin-bottom: 25px;
  font-size: 14px;
  color: #606266;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 320px;
  gap: 30px;
}

.news-content {
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 15px;
  line-height: 1.4;
  color: #1a1a1a;
}

.meta {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  color: #666;
  font-size: 14px;
}

.meta > * {
  margin-right: 20px;
}

.meta .el-tag {
  padding: 0 8px;
}

.content {
  margin: 30px 0;
  line-height: 1.8;
  color: #2c3e50;
}

.html-content {
  line-height: 1.8;
}

.html-content :deep(p) {
  margin: 1em 0;
}

.html-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 1em 0;
  border-radius: 4px;
}

.html-content :deep(a) {
  color: #409eff;
  text-decoration: none;
}

.html-content :deep(a:hover) {
  text-decoration: underline;
}

.html-content :deep(h1),
.html-content :deep(h2),
.html-content :deep(h3),
.html-content :deep(h4),
.html-content :deep(h5),
.html-content :deep(h6) {
  margin: 1.5em 0 1em;
  line-height: 1.4;
}

.html-content :deep(ul),
.html-content :deep(ol) {
  padding-left: 2em;
  margin: 1em 0;
}

.html-content :deep(blockquote) {
  margin: 1em 0;
  padding: 0.5em 1em;
  border-left: 4px solid #409eff;
  background-color: #f8f9fa;
  color: #666;
}

.paragraph {
  margin: 1em 0;
  text-align: justify;
}

.image-container {
  margin: 30px 0;
  text-align: center;
}

.content-image {
  max-width: 100%;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-caption {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: center;
}

.quote {
  margin: 30px 0;
  padding: 15px 20px;
  border-left: 4px solid #409eff;
  background-color: #f5f7fa;
  font-style: italic;
  color: #666;
}

.related-section {
  margin-top: 40px;
  padding-top: 25px;
  border-top: 1px solid #eee;
}

.related-section h3 {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.related-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.related-item {
  padding: 10px 0;
  border-bottom: 1px dashed #eee;
}

.related-link {
  color: #333;
  font-size: 15px;
  line-height: 1.5;
  display: block;
  margin-bottom: 5px;
  transition: color 0.3s;
}

.related-link:hover {
  color: #409eff;
}

.related-time {
  font-size: 13px;
  color: #999;
}

.comments-section {
  margin-top: 50px;
  padding-top: 30px;
  border-top: 1px solid #eee;
}

.comments-section h2 {
  font-size: 22px;
  margin-bottom: 25px;
  color: #333;
}

.comment-item {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-avatar {
  margin-right: 15px;
}

.comment-content {
  flex: 1;
  width: calc(100% - 52px);
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.username {
  font-weight: bold;
  margin-right: 8px;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
  margin-right: auto;
}

.comment-text {
  color: #333;
  line-height: 1.6;
  margin-bottom: 8px;
  word-break: break-word;
}

.comment-input {
  margin-top: 30px;
}

.comment-actions {
  margin-top: 15px;
  text-align: right;
}

.sidebar {
  position: sticky;
  top: 20px;
  align-self: start;
}

.hot-news,
.ad-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.hot-news h3 {
  font-size: 18px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.hot-news h3 .el-icon {
  margin-right: 8px;
}

.hot-item {
  padding: 12px 0;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.hot-item:last-child {
  border-bottom: none;
}

.hot-rank {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background: #f5f5f5;
  border-radius: 50%;
  margin-right: 12px;
  font-size: 14px;
  color: #666;
}

.hot-item.top-three .hot-rank {
  background: #409eff;
  color: #fff;
}

.hot-link {
  flex: 1;
  color: #333;
  font-size: 15px;
  line-height: 1.4;
  transition: color 0.3s;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.hot-link:hover {
  color: #409eff;
}

.hot-views {
  font-size: 13px;
  color: #999;
  margin-left: 10px;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.hot-views .el-icon {
  margin-right: 3px;
}

.ad-section {
  text-align: center;
}

.ad-image {
  width: 100%;
  border-radius: 4px;
}

.ad-text {
  margin-top: 8px;
  font-size: 13px;
  color: #999;
}

.error-container {
  background: #fff;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.image-error .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.no-comments {
  padding: 40px 0;
  text-align: center;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 30px 0;
  padding: 20px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 10px 25px;
  font-size: 15px;
}

.action-button .count {
  margin-left: 5px;
  font-size: 14px;
  color: #909399;
}

.action-button :deep(.el-icon) {
  font-size: 18px;
}
.ad-container {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.ad-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.child-comments {
  margin-top: 8px;
}

.toggle-replies {
  margin-bottom: 8px;
}

.toggle-button {
  display: inline-flex;
  align-items: center;
  padding: 0;
  font-size: 12px;
  color: #8590a6;
  transition: color 0.2s;
}

.toggle-icon {
  margin-right: 4px;
  font-size: 12px;
  color: #8590a6;
  transition: color 0.2s;
}

.toggle-replies:hover .toggle-button,
.toggle-replies:hover .toggle-icon {
  color: #409eff;
}

.child-comments-container {
  padding-left: 16px;
  border-left: 2px solid #ebebeb;
  margin-top: 8px;
}

.child-comment-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.child-comment-item:last-child {
  border-bottom: none;
}

.child-comment-content {
  flex: 1;
  margin-left: 10px;
}

.show-more-replies {
  margin-top: 10px;
  padding-left: 40px;
  cursor: pointer;
  color: #409eff;
}

.delete-button {
  font-size: 12px;
  color: #8590a6;
  padding: 0 8px;
  margin-left: 8px;
}

.delete-button:hover {
  opacity:#f56c6c;
}

.reply-button {
  font-size: 12px;
  color: #8590a6;
  padding: 0 8px;
  margin-left: 8px;
}

.reply-button:hover {
  color: #409eff;
}

.reply-input {
  margin: 12px 0;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.reply-actions {
  margin-top: 8px;
  text-align: right;
}

.load-more-comments {
  text-align: center;
  margin: 20px 0;
}

.load-more-comments .toggle-button {
  display: inline-flex;
  align-items: center;
  padding: 0;
  font-size: 14px;
  color: #8590a6;
  transition: color 0.2s;
}

.load-more-comments .toggle-icon {
  margin-right: 4px;
  font-size: 14px;
  color: #8590a6;
  transition: color 0.2s;
}

.load-more-comments .toggle-button:hover,
.load-more-comments .toggle-button:hover .toggle-icon {
  color: #409eff;
}
</style>
